package cn.lblbc.webbrowser.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**
 * 权限管理工具类
 */
class PermissionManager(private val context: Context) {
    
    companion object {
        const val PERMISSION_REQUEST_CODE = 1001
        
        // 存储权限 - 根据Android版本区分
        val STORAGE_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ (API 33+) 不再需要READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限
            // 对于下载管理器，应用可以访问自己创建的文件，无需特殊权限
            arrayOf()
        } else {
            // Android 12及以下版本需要传统存储权限
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        }
        
        // 通知权限 (Android 13+)
        val NOTIFICATION_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.POST_NOTIFICATIONS)
        } else {
            arrayOf()
        }
        
        // 所有需要的权限
        val ALL_PERMISSIONS = STORAGE_PERMISSIONS + NOTIFICATION_PERMISSIONS
    }
    
    /**
     * 检查是否有所有必要的权限
     */
    fun hasAllPermissions(): Boolean {
        // Android 13+ 不需要检查存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            println("PermissionManager: Android 13+不需要存储权限")
            return true
        }
        
        val permissionsToCheck = mutableListOf<String>()
        
        // 存储权限 (Android 6.0+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionsToCheck.addAll(STORAGE_PERMISSIONS)
            println("PermissionManager: 需要检查的存储权限: ${STORAGE_PERMISSIONS.joinToString()}")
        }
        
        // 检查存储权限
        val result = permissionsToCheck.isEmpty() || permissionsToCheck.all { permission ->
            val granted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
            println("PermissionManager: 权限 $permission: ${if (granted) "已授予" else "未授予"}")
            granted
        }
        
        println("PermissionManager: 所有权限检查结果: $result")
        return result
    }
    
    /**
     * 请求所有必要的权限
     */
    fun requestAllPermissions(activity: Activity) {
        println("PermissionManager: 开始请求权限")
        
        // Android 13+ 不需要请求存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            println("PermissionManager: Android 13+不需要请求存储权限")
            
            // 检查是否需要通知权限
            if (NOTIFICATION_PERMISSIONS.isNotEmpty()) {
                val needNotificationPermission = NOTIFICATION_PERMISSIONS.any { permission ->
                    val granted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
                    !granted
                }
                
                if (needNotificationPermission) {
                    println("PermissionManager: 需要请求通知权限")
                    ActivityCompat.requestPermissions(
                        activity,
                        NOTIFICATION_PERMISSIONS,
                        PERMISSION_REQUEST_CODE
                    )
                } else {
                    println("PermissionManager: 已有通知权限")
                }
            }
            
            return
        }
        
        val permissionsToRequest = mutableListOf<String>()
        
        // 存储权限 (Android 6.0+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            STORAGE_PERMISSIONS.forEach { permission ->
                val granted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
                println("PermissionManager: 检查权限 $permission: ${if (granted) "已授予" else "未授予"}")
                
                if (!granted) {
                    permissionsToRequest.add(permission)
                }
            }
        }
        
        // 请求所有需要的权限
        if (permissionsToRequest.isNotEmpty()) {
            println("PermissionManager: 请求权限: ${permissionsToRequest.joinToString()}")
            ActivityCompat.requestPermissions(
                activity,
                permissionsToRequest.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
        } else {
            println("PermissionManager: 已有所有需要的权限")
        }
    }
    
    /**
     * 检查特定权限是否被授予
     */
    fun isPermissionGranted(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
    }
}